

var answerFied1;
var queryField1;
var lookupURL1;
var divName1;
var ifName1;
var lastVal1 = "";
var val1 = "";
var xmlHttp1;
var cache1 = new Object();
var searching1 = false;
var globalDiv1;
var divFormatted1 = false;
var DIV_BG_COLOR1 = "#eeeeee";
var DIV_HIGHLIGHT_COLOR1 = "#cccccc";
var array_datos1 = new Array();//datos del array
var array_datos1_id = new Array();
/**
The InitQueryCode1 function should be called by the <body onload> event, passing
at least the queryField1Name and lookupURL1Prefix parameters, where:

queryField1Name = the name of the form field we're using for lookups
lookupURL1Prefix = the URL we'll use to pass the query string back to the server,
                  which will be immediately proceeded by the query string

For example:
<body onload="InitQueryCode1('lookupField', 'http://lookupserver/QueryHandler?q=')">

The above example will monitor the input box called "lookupField" on this page,
and when it changes the contents of the field will be passed to lookupserver like:
http://lookupserver/QueryHandler?q=fieldValue

The http://lookupserver/QueryHandler will be expected to return a text response
with a single line of text that calls the showQueryDiv1 function, in a format like:
showQueryDiv1("smi", new Array("John Smith", "Mary Smith"), new Array("555-1212", "555-1234"));

*/
function InitQueryCode1(queryField1Name, lookupURL1Prefix, hiddenDivName,caja_dato_concatenado)
{
  queryField1 = document.getElementsByName(queryField1Name).item(0);
  answerFied1 = document.getElementsByName(caja_dato_concatenado).item(0);
  //answerFied1 = document.getElementsByName('busca_rapida').item(0);
 // var nume_fila = document.getElementsByName('nume_fila').item(0);

	//nume_fila.value=1;

  queryField1.onblur = hideDiv1;
  queryField1.onkeydown = keypressHandler1;

  // for some reason, Firefox 1.0 doesn't allow us to set autocomplete to off
  // this way, so you should manually set autocomplete="off" in the input tag
  // if you can -- we'll try to set it here in case you forget
  queryField1.autocomplete = "off";

  lookupURL1 = lookupURL1Prefix;

  if (hiddenDivName)
    divName1 = hiddenDivName;
  else
    divName1 = "querydiv";
  ifName1 = "queryiframe";

  // add a blank value to the cache1 (so we don't try to do a lookup when the
  // field is empty) and start checking for changes to the input field

  addToCache1("", new Array(), new Array());
  //setTimeout("mainLoop()", 10000);

}


/**
This is a helper function that just adds results to our cache1, to avoid
repeat lookups.
*/
function addToCache1 (queryString, resultArray1, resultArray2)
{
	var name;
	name=divName1+"-"+queryString;
	cache1[queryString] = new Array(resultArray1, resultArray2);

}


/**
This is the function that monitors the queryField1, and calls the lookup
functions when the queryField1 value changes.
*/
function inicio1() {

  val1 = escape(queryField1.value);
  var nombre;
  // if the field value has changed and we're not currently waiting for
  // a lookup result to be returned, do a lookup (or use the cache1, if
  // we can)
  //comienza a contar sobre el 3 caracter

  if(val1.length>2){

      if( searching1 == false){

			nombre=divName1+"-"+val1;

            var cache1Result = cache1[nombre];

			//alert(cache1Result[0]);
            if (cache1Result){

              	showQueryDiv(val1, cache1Result[0], cache1Result[1]);

            }else{

				   doRemoteQuery1(val1);

               }

       }
    }else{
            // si en menor a dos la longitud de los caracteres no muestra
            showDiv1(false);


    }
	lastVal1 = val1;
  //setTimeout("mainLoop()", 10000);
  return true;
}



/**
Get the <DIV> we're using to display the lookup results, and create the
<DIV> if it doesn't already exist.
*/
function getDiv1 (divID)
{
	  // figure out where the top corner of the div should be, based on the
    // bottom left corner of the input field
    var x = queryField1.offsetLeft;

    var y = queryField1.offsetTop + queryField1.offsetHeight;
    var parent = queryField1;
    while (parent.offsetParent) {
      parent = parent.offsetParent;
      x += parent.offsetLeft;
      y += parent.offsetTop;
    }

  if (!globalDiv1) {
    // if the div doesn't exist on the page already, create it
    if (!document.getElementById(divID)) {
      var newNode = document.createElement("div");
      newNode.setAttribute("id", divID);
      document.body.appendChild(newNode);
    }

    // set the globalDiv1 reference
    globalDiv1 = document.getElementById(divID);
	//alert(queryField1.name);

    // add some formatting to the div, if we haven't already
    if (!divFormatted1) {
      globalDiv1.style.backgroundColor = DIV_BG_COLOR1;
      globalDiv1.style.fontFamily = "Verdana, Geneva, Arial, Helvetica, sans-serif";
      globalDiv1.style.padding = "4px";
      globalDiv1.style.border = "1px solid black";
      globalDiv1.style.fontSize = "90%";
      globalDiv1.style.position = "absolute";
      globalDiv1.style.left = x + "px";
      globalDiv1.style.top = y + "px";
      globalDiv1.style.visibility = "hidden";
      globalDiv1.style.zIndex = 10000;


      divFormatted1 = true;
    }
 }else{
 	globalDiv1.style.left = x + "px";
    globalDiv1.style.top = y + "px";

 }

  return globalDiv1;
}


/**
This is the function that should be returned by the XMLHTTP call. It will
format and display the lookup results.
*/
function showQueryDiv1(queryString, resultArray1, resultArray2)
{
  var div = getDiv1(divName1);
	for (z=0;z<array_datos1.length;z++){
		array_datos1[z] = null
	}
  // remove any results that are already there
  while (div.childNodes.length > 0)
    div.removeChild(div.childNodes[0]);

  // add an entry for each of the results in the resultArray
  for (var i = 0; i < resultArray1.length; i++)
  {
    // each result will be contained within its own div
    var result = document.createElement("div");
    result.style.cursor = "pointer";
    result.style.borderBottom = "1px solid #777777";
    result.style.padding = "3px 0px 3px 0px";
    _unhighlightResult1(result);
    result.onmousedown = selectResult1;
    result.onmouseover = highlightResult1;
    result.onmouseout = unhighlightResult1;

    var result1 = document.createElement("span");
    result1.className = "result1";
    result1.style.textAlign = "left";
    result1.style.fontWeight = "bold";
    result1.innerHTML = (i+1)+") "+resultArray1[i];

    //var result2 = document.createElement("span");
    //result2.className = "result2";
    //result2.style.textAlign = "right";
    //result2.style.paddingLeft = "20px";
    //result2.innerHTML = resultArray2[i];
    //array_datos1 = new Array();
	array_datos1_id[i]=resultArray1[i];
    array_datos1[i]= resultArray2[i];
    //alert(resultArray2[i]);

    result.appendChild(result1);
    //result.appendChild(result2);
    div.appendChild(result);
  }

  // if this resultset isn't already in our cache1, add it
	var nombre;
	nombre=divName1+"-"+queryString;
	//alert(nombre);
  var isCached = cache1[queryString];
   //alert("isCached");
   //alert(isCached);
   //alert(queryString);
 if (!isCached){
   //alert("entra al cache1");
   //no funciona el cache1

    addToCache1(queryString, resultArray1, resultArray2);
  }


  // display the div if we had at least one result
  showDiv1(resultArray1.length > 0);
}


/**
This is called whenever the user clicks one of the lookup results.
It puts the value of the result in the queryField1 and hides the
lookup div.
*/
function selectResult1()
{
  _selectResult1(this);
}


/** This actually fills the field with the selected result and hides the div */
function _selectResult1(item)
{

  var pos;
  var donde;
  var texto;
  var spans = item.getElementsByTagName("span");

  answerFied1.value="";
  if (spans) {
    for (var i = 0; i < spans.length; i++) {
      if (spans[i].className == "result1") {

        queryField1.value = spans[i].innerHTML;
        texto=queryField1.value;
        lastVal1 = val1 = escape(queryField1.value);
		donde=texto.indexOf(")");
		pos=texto.substring(0,donde);
		pos=parseInt(pos)-1;
		queryField1.value=texto.substring(donde+2);
		//donde=encontrar1(queryField1.value);
		//alert(donde);
		//alert(array_datos1.length);

		answerFied1.value=array_datos1[pos];
        queryField1.style.backgroundColor="#FFFFCC";
        //alert("ver"+answerFied1.value);
		//answerFied1.value=array_datos1[pos];
       	//alert(answerFied1.value);
        //debugger;
        searching1 = false;
       	inicio1();
        //alert(queryField1.id);
        queryField1.focus();
        showDiv1(false);
        return;
      }
    }
  }
}

function encontrar1(aguja){
	var i;

	for(i=0;i<array_datos1.length;i++){

		if(array_datos1_id[i]== aguja){

			break;
		}
	}
	return  i;

}



/**
This is called when a user mouses over a lookup result
*/
function highlightResult1()
{
  _highlightResult1(this);
}

/** This actually highlights the selected result */
function _highlightResult1(item)
{
  item.style.backgroundColor = DIV_HIGHLIGHT_COLOR1;
}


/**
This is called when a user mouses away from a lookup result
*/
function unhighlightResult1()
{
  _unhighlightResult1(this);
}

/** This actually unhighlights the selected result */
function _unhighlightResult1(item)
{
  item.style.backgroundColor = DIV_BG_COLOR1;
}


/**
This either shows or hides the lookup div, depending on the value of

the "show" parameter.
*/
function showDiv1 (show)
{
  var div = getDiv1(divName1);
  if (show)
    div.style.visibility = "visible";
  else
    div.style.visibility = "hidden";

  adjustiFrame1();
}


/**
We originally used showDiv1 as the function that was called by the onBlur
event of the field, but it turns out that Firefox will pass an event as the first
parameter of the function, which would cause the div to always be visible.
So onBlur now calls hideDiv1 instead.
*/
function hideDiv1 ()
{
  showDiv1(false);
}


/**
Use an "iFrame shim" to deal with problems where the lookup div shows up behind
selection list elements, if they're below the queryField1. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame1()
{
  if (!document.getElementById(ifName1)) {

    var newNode = document.createElement("iFrame");
    newNode.setAttribute("id", ifName1);
    newNode.setAttribute("src", "javascript:false;");
    newNode.setAttribute("scrolling", "no");
    newNode.setAttribute("frameborder", "0");
    document.body.appendChild(newNode);
  }

  iFrameDiv = document.getElementById(ifName1);
  var div = getDiv1(divName1);

  try {
    iFrameDiv.style.position = "absolute";
    iFrameDiv.style.width = div.offsetWidth;
    iFrameDiv.style.height = div.offsetHeight;
    iFrameDiv.style.top = div.style.top;
    iFrameDiv.style.left = div.style.left;
    iFrameDiv.style.zIndex = div.style.zIndex - 1;
    iFrameDiv.style.visibility = div.style.visibility;
  } catch(e) {
  }
}


/**
This sets up the XMLHTTP object we're using for the dynamic lookups.
*/
function getXMLHTTP1(){
  var A = null;

  try{
    A = new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
    try{
      A = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(oc){
      A = null;
    }
  }

  if(!A && typeof XMLHttpRequest != "undefined") {
    A = new XMLHttpRequest();
  }

  return A;
}


/**
This actually sends the lookup request (as a URL with a query string) to a
server in the background. When a response comes back from the server, the
function attached to the onReadyStateChange event is fired off.
*/
function doRemoteQuery1 (queryString)
{
  searching1 = true;
  if(xmlHttp1 && xmlHttp1.readyState != 0) {
    xmlHttp1.abort()
  }

  xmlHttp1=getXMLHTTP1();
  if(xmlHttp1){
    xmlHttp1.open("GET", lookupURL1 + queryString, true);
	//queryField1.value=lookupURL1 + queryString;

    // What do we do when the response comes back?
    xmlHttp1.onreadystatechange = function() {

      if (xmlHttp1.readyState == 4 && xmlHttp1.responseText && searching1) {
        //alert(xmlHttp1.responseText);
        eval(xmlHttp1.responseText);

        searching1 = false;
      }
    }

    xmlHttp1.send(null);

  }

}


/**
This is the key handler function, for when a user presses the up arrow,
down arrow, tab key, or enter key from the input field.
*/
function keypressHandler1 (evt)
{
 queryField1.style.backgroundColor="#FCB4C0"
  var KEYUP = 38;
  var KEYDOWN = 40;
  var KEYENTER = 13;
  var KEYTAB = 9;
   if(!evt && window.event) {
    evt = window.event;
  }
  var key = evt.keyCode;
  // don't do anything if the div is hidden
  var div = getDiv1(divName1);
  if (div.style.visibility == "hidden"){
      if (key == KEYTAB){
   		 inicio1();
		 return false;
  		}
	return true;
  }else{

       if ((key != KEYUP) && (key != KEYDOWN) && (key != KEYENTER) && (key != KEYTAB)){
        if(lastVal1==val1){
            if (div.style.visibility != "hidden"){
              showDiv1(false);
           // inicio1();
              return true;
              }
          }
       }
  }


  // make sure we have a valid event variable
  // if this key isn't one of the ones we care about, just return
  if ((key != KEYUP) && (key != KEYDOWN) && (key != KEYENTER) && (key != KEYTAB)){
       showDiv1(false);
       inicio1();
       return true;
  }

  // get the span that's currently selected, and perform an appropriate action
  var selNum = getSelectedSpanNum1(div);
  var selSpan = setSelectedSpan1(div, selNum);

  if ((key == KEYENTER) || (key == KEYTAB)) {
    if (selSpan)
      _selectResult1(selSpan);
    evt.cancelBubble=true;
    return false;
  } else {
    if (key == KEYUP)
      selSpan = setSelectedSpan1(div, selNum - 1);
    if (key == KEYDOWN)
      selSpan = setSelectedSpan1(div, selNum + 1);
    if (selSpan)
      _highlightResult1(selSpan);
  }

  showDiv1(true);
  return true;
}


/**
Get the number of the result that's currently selected/highlighted
(the first result is 0, the second is 1, etc.)
*/
function getSelectedSpanNum1 (div)
{
  var count = -1;
  var spans = div.getElementsByTagName("div");
  if (spans) {
    for (var i = 0; i < spans.length; i++) {
      count++;
      if (spans[i].style.backgroundColor != div.style.backgroundColor)
        return count;
    }
  }

  return -1;
}


/**
Select/highlight the result at the given position
*/
function setSelectedSpan1 (div, spanNum)
{
  var count = -1;
  var thisSpan;
  var spans = div.getElementsByTagName("div");
  if (spans) {
    for (var i = 0; i < spans.length; i++) {
      if (++count == spanNum) {
        _highlightResult1(spans[i]);
        thisSpan = spans[i];
      } else {
        _unhighlightResult1(spans[i]);
      }
    }
  }

  return thisSpan;
}

//////////////////////////////////////////////

// JavaScript Document





